package server;


import gui.InitWindow;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

import client.ChatClient;
import chatInterface.*;

public class Server {
	
	private static String ip,myip;	
	private static int port,myport;
	private static String name,myname;
	public static InitWindow win;
	
	public static void main(String[] args) {
		System.setProperty("javax.net.ssl.keyStore" , "./run/keystore");
        System.setProperty("javax.net.ssl.keyStorePassword" , "chat123");
        System.setProperty("javax.net.ssl.trustStore" , "./run/truststore");
        System.setProperty("javax.net.ssl.trustStorePassword" , "chat123");
		// vytvorime security managera, konfigurace je specifikovana bud pomoci -Djava.security.policy=file.policy
		//if (System.getSecurityManager() == null)
		//	System.setSecurityManager(new RMISecurityManager());
		if(args.length==3){
			myname=args[0];
			myip=args[1];
			myport=Integer.valueOf(args[2]);
		}else if(args.length==6){
			myname=args[0];
			myip=args[1];
			myport=Integer.valueOf(args[2]);
			name=args[3];
			ip=args[4];
			port=Integer.valueOf(args[5]);
		}
		else {
			System.out.println("! Spatny pocet parametru !");
			System.out.println("Format: (prvni) mojename mojeip mujport");
			System.out.println("Format: (ostatni) mojename mojeip mujport name ip port");
			return;
		}
		// Zobrazeni uvodniho okna
		win = new InitWindow();
		try {
			Interface msi;
			if(args.length==6)msi = new ServerImpl(myname,myip,myport,name,ip,port);
			else msi = new ServerImpl(myname, myip, myport);
			SslRMIClientSocketFactory ssl = new SslRMIClientSocketFactory();
			SslRMIServerSocketFactory fac= new SslRMIServerSocketFactory();
			Registry registry = LocateRegistry.createRegistry(myport,new SslRMIClientSocketFactory(),new SslRMIServerSocketFactory());
			Interface stub = (Interface) UnicastRemoteObject.exportObject(msi, myport, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());
			System.out.println("HHHHH");
			registry = LocateRegistry.getRegistry(myip, myport,new SslRMIClientSocketFactory());
			registry.rebind(myname, stub);
			System.out.println("Server " + myname + " " + "("+myip+":"+myport+") bezi");
			if(args.length==6)msi.createLocalClient();
		}
		catch (Exception e) {
			System.err.println("Data exception: " + e.getMessage());
		}
	}

	public static InitWindow getInitWindow(){
		return win;
	}
}